<script lang="ts" setup>
import { onMounted, ref } from 'vue'

defineOptions({ name: 'SDialog' })

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  showClose: {
    type: Boolean,
    default: true,
  },
  title: {
    type: String,
    default: '提示',
  },
  beforeClose: Function, // 关闭前的回调函数
  modal: {
    type: Boolean,
    default: true,
  },
  center: {
    type: Boolean,
    default: false,
  },
  top: {
    type: String,
    default: '15vh',
  },
  width: {
    type: String,
    default: '500px',
  },
  closeOnClickModal: {
    type: Boolean,
    default: true,
  },
})

const wrapper = ref<HTMLElement>()
const dialog = ref<HTMLElement>()
onMounted(() => {
  if (props.visible) {
    wrapper.value?.focus()
  }
})

const emit = defineEmits<{
  (e: 'opened'): void
  (e: 'closed'): void // 动画结束时的回调
  (e: 'update:visible', value: boolean): void
  (e: 'close'): void
}>()

const afterEnter = () => {
  emit('opened')
}

const afterLeave = () => {
  emit('closed')
}

const handleClose = () => {
  // 如果关闭前的回调含存在，就执行回调
  if (props.beforeClose) {
    props.beforeClose(hide)
  } else {
    hide()
  }
}

const handleWrapperClick = () => {
  if (props.closeOnClickModal) {
    handleClose()
  }
}

const hide = () => {
  emit('update:visible', false)
  emit('close')
}
</script>

<template>
  <transition
    name="dialog-fade"
    @after-enter="afterEnter"
    @after-leave="afterLeave">
    <div
      class="S-dialog__wrapper v-modal"
      v-if="visible"
      @click.self="handleWrapperClick"
      ref="wrapper">
      <div class="S-dialog" ref="dialog">
        <div class="S-dialog__header">
          <span class="S-dialog__title">{{ title }}</span>
          <button
            type="button"
            class="S-dialog__headerbtn"
            v-if="showClose"
            @click="handleClose">
            <i class="iconfont icon-guanbi"></i>
          </button>
        </div>
        <div class="S-dialog__body" v-if="$slots.body">
          <slot name="body"></slot>
        </div>
        <div class="S-dialog__footer" v-if="$slots.footer">
          <slot name="footer"></slot>
        </div>
      </div>
    </div>
  </transition>
</template>
